require(Hmisc, keep.source=F );
require(stats, keep.source=F );

get.pval.ttest.onesample <- function ( data, Mean ) {
  f <- function ( i ) {
    t <-  t.test ( data[i,], mu=Mean );
    return (c(t$p.value,t$conf.int[[1]], t$estimate, t$conf.int[[2]]) );
  }

  return ( sapply ( 1:nrow(data), f ) );
}

get.pval.ttest.twosample <- function ( dataf, index1, index2, datafilter=as.numeric ) {
  f <- function(i) {
    t <- t.test(datafilter(dataf[i,index1]),datafilter(dataf[i,index2]))
      return ( c ( t$p.value, t$conf.int[[1]], t$estimate[[1]] - t$estimate[[2]], t$conf.int[[2]] ) );
  }
  return ( sapply ( 1:length ( dataf[,1] ),f ) );
}

p.adjust.holm <-function(p,n=length(p)) {
  r<-rank(p);
  index<-order(p);
  qi<-p*(n+1-r);
  for (i in 2:length(p)) {
    qi[index[i]]<-max(qi[index[i]], qi[index[i-1]]);
  }
  list(adjp=pmin(qi,1),p=p,method="Holm");
}

p.adjust.hochberg <-function(p) {
  n<-length(p);
  r<-rank(p);
  index<-order(p);
  qi<-p*(n+1-r);
  for (i in (n-1):1) {
    qi[index[i]]<-min(qi[index[i]], qi[index[i+1]]);
  }
  list(adjp=qi,p=p,method="Hochberg");
}

p.adjust.bonferroni<-function(p,n=length(p)){
  list(adjp=pmin(p*n,1),p=p,method="Bonferroni");
}

p.adjust <- function (p, method = c("hochberg", "holm", "bonferroni"), ...) {
  how <- match.arg(method);
  FUN <- get(paste("p.adjust", how, sep = "."));
  FUN(p, ...);
}

#p.adjust<-function(p,method=c("hochberg","holm","bonferroni"),...){
#  how<-pmatch(method[1],c("hochberg","holm","bonferroni"))
#  if (is.na(how)) stop(paste("Don't know method:",method))
#  m<-match.call()
#  m[[1]]<-as.name(paste("p.adjust",c("hochberg","holm","bonferroni")[how],sep="."))
#  m$method<-NULL
#  eval(m,sys.parent())
#}
